<?php

namespace Drupal\shushengyuan\Schemas;

use Drupal\shusy_favorite_product\Entity\ShusyFavoriteProduct;
use Drupal\shusy_product\Entity\ShusyProduct;
use Drupal\shusy_product\Entity\ShusyProductStandard;
use Drupal\shusy_product_in_store\Entity\ShusyProductInStore;
use Drupal\shusy_product_miaosha\Entity\ShusyProductMiaoshaStandard;
use Drupal\shusy_product_parameter\Entity\ShusyProductParameter;
use Drupal\shusy_product_pintuan\Entity\ShusyProductPintuan;
use Drupal\shusy_product_standards\Entity\ShusyProductStandards;
use Drupal\shusy_product_standards\Entity\ShusyProductStandardsItems;
use EntityListWrapper;
use Exception;

/**
 * @OA\Schema(
 *   schema="ProductItemInfo",
 *   type="object",
 *   description="ProductItemInfo",
 *   allOf={
 *       @OA\Schema(ref="#/components/schemas/ProductItem"),
 *   }
 * )
 */
class ProductItemInfo extends ProductItem {

  protected function setValue() {
    parent::setValue();
    if ($this->entity instanceof ShusyProduct) {
      [$type] = $this->context;

      $images = [];
      $field_images = $this->wrapper->field_images;
      if ($field_images instanceof EntityListWrapper) {
        foreach ($field_images as $image) {
          $images[] = $this->imageStyleUrl('ProductItemInfoImages', $image->value());
        }
      }
      $value = [
        'type' => (int) $type,
        /**
         * @OA\Property(
         *   property="images",
         *   type="array",
         *   description="轮播图",
         *   @OA\Items(type="string")
         * ),
         */
        'images' => $images,
        /**
         * @OA\Property(
         *   property="parameters",
         *   type="array",
         *   description="参数",
         *   @OA\Items(type="object",
         *   @OA\Property(property="label",type="string",description="参数名"),
         *   @OA\Property(property="value",type="string",description="参数值"),
         *   )
         * ),
         */
        'parameters' => $this->getParameters($this->entity),
        /**
         * @OA\Property(
         *   property="store",
         *   type="object",
         *   description="所属店铺",
         *   ref="#/components/schemas/StoreItem",
         * ),
         */
        'store' => $this->getStore($this->entity),
        /**
         * @OA\Property(
         *   property="body",
         *   type="string",
         *   description="详情富文本",
         * ),
         */
        'body' => $this->wrapper->field_body->value()['safe_value'],
        /**
         * @OA\Property(
         *   property="favorite",
         *   type="integer",
         *   description="是否收藏 0 否 1 是",
         * ),
         */
        'favorite' => $this->getFavorite($this->entity),
        /**
         * @OA\Property(
         *   property="poster",
         *   type="string",
         *   description="海报图",
         * ),
         */
        'poster' => (string) $this->getPoster($this->entity, $type),
        //小程序分享信息
        // /pages/preload/preload?id=${id}&uid=${uid}&op=${op}&type=${type}&ptid=${ptid}
        'share' => $this->getShare($this->entity, $type),
      ];
      $this->merge($value);

      $value = [
        //是否购买过此商品 并评论过 购买过允许追加评论
        'add' => (bool) $this->getAdd($this->entity),
      ];
      $this->merge($value);

      $this->getMultiStandards();
    }
  }

  protected function getMultiStandards() {
    $actives = [];
    $ps = shusy_product_standards_load_multiple(FALSE, [
      'product_id' => $this->entity->id,
      'status' => 1,
    ]);
    $list = [];
    $stmps = [];
    foreach ($ps as $p) {
      if ($p instanceof ShusyProductStandards) {
        if (empty($list[$p->id])) {
          $list[$p->id] = [
            'name' => $p->standard,
            'child' => [],
          ];
        }
        $child = [];
        $items = shusy_product_standards_items_load_multiple(FALSE, ['spstandard_id' => $p->id]);
        foreach ($items as $item) {
          if ($item instanceof ShusyProductStandardsItems) {
            $child[] = [
              'id' => (int) $item->id,
              'name' => $item->standard,
              'standard_id' => $item->standard_id,
            ];
            $stmps[$item->standard_id][$p->id] = (int) $item->id;
          }
        }
        $list[$p->id]['child'] = $child;
        $actives[] = 0;
      }
    }

    $multistandards = FALSE;
    foreach ($stmps as $standardId => $stmp) {
      $type = implode('-', $stmp);
      $multistandards[$type] = Standard::get($standardId);
    }
    $types = [];
    if (!empty($stmps)) {
      $types = array_values(array_shift($stmps));
    }
    $activeType = implode('-', $types);

    $value = [
      'spec_list' => array_values($list),
      'multistandards' => $multistandards,
      'actives' => $actives,
      'types' => $types,
      'activeType' => $activeType,
    ];
    $this->merge($value);
  }

  protected function getShare(ShusyProduct $product, int $type) {
    $uid = $this->getUid();
    $id = $product->id;
    return [
      'title' => $this->entity->name,
      'imageUrl' => $this->value['image'],
      'path' => "/pages/preload/preload?id=$id&uid=$uid&op=product&type=$type",
    ];
  }

  protected function getAdd(ShusyProduct $product) {
    $uid = $this->getUid();
    $query = db_select('shusy_product_comment', 'p');
    $query->fields('p', ['id']);
    $query->condition('product_id', $product->id);
    $query->condition('uid', $uid);
    $query->range(0, 1);
    $query->orderBy('id');
    return $query->execute()->rowCount();
  }

  /**
   * @param \Drupal\shusy_product\Entity\ShusyProduct $product
   * @param int $type 1 默认详情  2 秒杀详情 3去拼团 4 拼团详情
   *
   * @return false|mixed|string
   */
  protected function getPoster(ShusyProduct $product, int $type) {
    //生成海报
    $uid = $this->getUid();
    $id = $product->id;
    $share = variable_get_value('shushengyuan:poster:product');
    //商品海报需要合成 不能检测二维码
    $posterVars = [];

    $uri = wx_mini_qr_create('shushengyuan', "share_product_{$uid}_{$id}_{$type}", [
      'uid' => $uid,
      'product' => $id,
      'type' => 'share_product',
      'sType' => $type,
    ]);
    $posterVars[] = [
      'type' => 'avatar',
      'sets' => [
        'size' => 150,
        'left' => 515,
        'bottom' => 125,
        'mode' => 'square',
        'uri' => $uri,
      ],
    ];
    $avatar = $this->getAvatar();
    $posterVars[] = [
      'type' => 'avatar',
      'sets' => [
        'size' => 90,
        'left' => 45,
        'bottom' => 200,
        'mode' => 'circle',
        'uri' => $avatar,
      ],
    ];
    //商品图
    $fieldImage = $this->getImage();
    $posterVars[] = [
      'type' => 'image',
      'sets' => [
        'size' => 580,
        'left' => 85,
        'bottom' => 650,
        'uri' => $fieldImage['uri'],
      ],
    ];
    $posterVars[] = [
      'type' => 'customtext',
      'sets' => [
        'size' => 28,
        'color' => '#333333',
        'left' => 85,
        'bottom' => 560,
        'text' => $product->name,
        'width' => 580,
        'height' => 60,
      ],
    ];
    //现价:¥
    $posterVars[] = [
      'type' => 'customtext',
      'sets' => [
        'size' => 32,
        'color' => '#e1292b',
        'left' => 125,
        'bottom' => 480,
        'text' => "现价:¥ " . $this->convertYuan($this->getPrice()),
        'width' => 280,
        'height' => 55,
      ],
    ];
    //原价:¥
    $posterVars[] = [
      'type' => 'customtext',
      'sets' => [
        'size' => 24,
        'color' => '#999999',
        'left' => 430,
        'bottom' => 480,
        'text' => "原价:¥ " . $this->convertYuan($this->getCost()),
        'width' => 180,
        'height' => 35,
      ],
    ];


    $store = $this->getStore($product);
    if (!empty($store)) {
      //电话
      $posterVars[] = [
        'type' => 'customtext',
        'sets' => [
          'size' => 24,
          'color' => '#fcf4f1',
          'left' => 85,
          'bottom' => 132,
          'text' => "电话: " . $store['tel'],
          'width' => 400,
          'height' => 32,
        ],
      ];
      //地址
      $posterVars[] = [
        'type' => 'customtext',
        'sets' => [
          'size' => 16,
          'color' => '#fcf4f1',
          'left' => 85,
          'bottom' => 75,
          'text' => "地址: " . $store['address'],
          'width' => 360,
          'height' => 35,
        ],
      ];
    }

    $image = imagecache_actions_image_load($share);
    image_scale($image, 748, NULL, TRUE);
    $this->posterGenerateVars($image, $posterVars);
    $dir = "public://poster";
    if (empty(file_prepare_directory($dir))) {
      drupal_mkdir($dir, 0777, TRUE);
    }
    $pid = $product->id;
    $destination = "public://poster/{$pid}-{$uid}.png";
    image_save($image, $destination);

    return file_create_url($destination);
  }

  protected function getParameters(ShusyProduct $shusyProduct) {
    $list = [];
    $es = shusy_product_parameter_load_multiple(FALSE, [
      'product_id' => $shusyProduct->id,
      'status' => 1,
    ]);
    foreach ($es as $e) {
      if ($e instanceof ShusyProductParameter) {
        $list[] = [
          'label' => $e->name,
          'value' => $e->info,
        ];
      }
    }
    return $list;
  }

  protected function getStore(ShusyProduct $shusyProduct) {
    $es = shusy_product_in_store_load_multiple(FALSE, ['product_id' => $shusyProduct->id]);
    if (!empty($es)) {
      $e = reset($es);
      if ($e instanceof ShusyProductInStore) {
        return StoreItem::get($e->store_id);
      }
    }
    return FALSE;
  }

  protected function getFavorite(ShusyProduct $shusyProduct) {
    $es = shusy_favorite_product_load_multiple(FALSE, [
      'product_id' => $shusyProduct->id,
      'uid' => $this->getUid(),
    ]);
    if (!empty($es)) {
      $e = reset($es);
      if ($e instanceof ShusyFavoriteProduct) {
        return $e->status;
      }
    }
    return 0;
  }

}
